package com.freemalll.merchant.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemalll.merchant.domain.entity.common.LogCallInterfaceEntity;
import com.freemalll.merchant.mapper.common.LogCallInterfaceMapper;
import com.freemalll.merchant.service.LogCallInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * Http操作工具类
 *
 * @author wbj
 */
@Slf4j
public class HttpClientUtil {


    public static String sendPost(String url, JSONObject header, String params, String interfaceName,
                                  String tableName, String relationshipId, int isLog) throws Exception {
        LogCallInterfaceEntity callLog = new LogCallInterfaceEntity();
        if (isLog != 2) {
            callLog.setInterfaceName(interfaceName);
            callLog.setRelationId(relationshipId);
            callLog.setRelationTable(tableName);
            callLog.setReqStatus("not_send");
            callLog.setReqTime(new Date());
        }
        if (isLog == 3 || isLog == 4) {
            callLog.setReqParam(params);
        }
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String respData = null;
        try {
            httpClient = HttpClients.custom().setSSLSocketFactory(AESUtil.createSSLConnSocketFactory()).build();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300000).build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            if (header != null) {
                for (String key : header.keySet()) {
                    post.addHeader(key, header.getString(key));
                }
            }
            post.addHeader("content-Type", "application/json");
            StringEntity entity = new StringEntity(params, "utf-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            if (isLog != 2) {
                callLog.setResTime(new Date());
            }
            HttpEntity resEntity = response.getEntity();
            if (resEntity == null) {
                if (isLog != 2) {
                    callLog.setReqStatus("send_error");
                }
                return respData;
            }
            respData = EntityUtils.toString(resEntity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            if (isLog != 2) {
                callLog.setMemo("接口请求异常：" + e.getMessage());
            }
            log.error("调用风控系统接口时异常：" + e.getMessage());
            throw e;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("风控系统客户端响应关闭异常：" + e.getMessage());
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("风控系统客户端连接关闭异常：" + e.getMessage());
                }
            }
            if (isLog != 2 && isLog != 4) {
                callLog.setResData(respData == null ? respData : respData.length() > 6000 ? respData.substring(0, 5000) : respData);
            }
            if (isLog != 2) {
                if (url.length() > 100) {
                    url = url.substring(url.lastIndexOf("/"));
                }
                callLog.setReqUrl(url);
            }
            try {
                if (isLog != 2) {
                    LogCallInterfaceMapper logCallInterfaceMapper = SpringUtil.getBean(LogCallInterfaceMapper.class);
                    logCallInterfaceMapper.insert(callLog);
                }
            } catch (Throwable t) {
                log.error("请求风控系统接口：" + url + "时，日志保存异常:" + t.getMessage());
            }
        }
        return respData;
    }

    public static String doPostTwo(String url, JSONObject header, String params, String interfaceName,
                                   String tableName, String relationshipId, int isLog) throws Exception {
        LogCallInterfaceEntity callLog = new LogCallInterfaceEntity();
        if (isLog != 2) {
            callLog.setInterfaceName(interfaceName);
            callLog.setRelationId(relationshipId);
            callLog.setRelationTable(tableName);
            callLog.setReqStatus("not_send");
            callLog.setReqTime(new Date());
        }
        if (isLog == 3 || isLog == 4) {
            callLog.setReqParam(params);
        }
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String respData = null;
        try {
            httpClient = HttpClients.custom().setSSLSocketFactory(AESUtil.createSSLConnSocketFactory()).build();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300000).build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            if (header != null) {
                for (String key : header.keySet()) {
                    post.addHeader(key, header.getString(key));
                }
            }
            post.addHeader("content-Type", "application/json");
            StringEntity entity = new StringEntity(params, "utf-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            if (isLog != 2) {
                callLog.setResTime(new Date());
            }
            HttpEntity resEntity = response.getEntity();
            if (resEntity == null) {
                if (isLog != 2) {
                    callLog.setReqStatus("send_error");
                }
                return respData;
            }
            respData = EntityUtils.toString(resEntity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            if (isLog != 2) {
                callLog.setMemo("接口请求异常：" + e.getMessage());
            }
            log.error("调用风控系统接口时异常：" + e.getMessage());
            throw e;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("风控系统客户端响应关闭异常：" + e.getMessage());
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("风控系统客户端连接关闭异常：" + e.getMessage());
                }
            }
            if (isLog != 2 && isLog != 4) {
                callLog.setResData(respData == null ? respData : respData.length() > 6000 ? respData.substring(0, 5000) : respData);
                if (null != respData) {
                    InputStream in_withcode = new ByteArrayInputStream(respData.getBytes("UTF-8"));
                    AliOSSUtil aliOSSUtil  = SpringUtil.getBean(AliOSSUtil.class);
                    String resUrl = aliOSSUtil.uploadFile(in_withcode, "riskResData", UUID.randomUUID().toString().replaceAll("-", "") + ".json");
                    callLog.setResData(resUrl);
                }
            }
            if (isLog != 2) {
                if (url.length() > 100) {
                    url = url.substring(url.lastIndexOf("/"));
                }
                callLog.setReqUrl(url);
            }
            try {
                if (isLog != 2) {
                    LogCallInterfaceService logCallInterfaceMapper = SpringUtil.getBean(LogCallInterfaceService.class);
                    logCallInterfaceMapper.save(callLog);
                }
            } catch (Throwable t) {
                log.error("请求风控系统接口：" + url + "时，日志保存异常:" + t.getMessage());
            }
        }
        return respData;
    }
}

